﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using CarparkBusiness;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CarparkIMS_CMS
{
    public class Worker : BackgroundService
    {
        public IServiceProvider Services { get; }
        public static CancellationTokenSource _CancelSource = new CancellationTokenSource() ;
        private static int needToClearCount = 0; 
        private static ILogger<Worker> Logger;
        private static ParkingSetting _ParkingSetting { get; set; }
        public Worker(IServiceProvider services, ILogger<Worker> logger, IOptions<ParkingSetting> parkingSetting)
        {
            Services = services;
            Logger = logger;
            _ParkingSetting = parkingSetting.Value; 
        }

        /// <summary>
        /// 2022-12-28
        /// </summary>
        /// <returns></returns>
        public  async Task CancelAsync()
        {
            await base.StopAsync(_CancelSource.Token);
            Console.WriteLine("Stop");
        }
        public override async Task StartAsync(CancellationToken cancellationToken)
        { 
            // DO YOUR STUFF HERE
            await base.StartAsync(_CancelSource.Token);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            // DO YOUR STUFF HERE
            await base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //async Task TaskAsync() => await Task.Run(async () => await TaskMainPortal());
            //await TaskAsync();

            await TaskMainPortal();

            while (true)
            {
                await Task.Delay(6000);
                string log = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}][WOKER BACKGROUND SERVICE IS RUNNING.....]";
                Logger.LogInformation(log);
                if (_CancelSource.IsCancellationRequested)
                    break;
            }
        }

        public static async Task TaskMainPortal()
        {
            string log = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}][WOKER BACKGROUND SERVICE IS RUNNING.....]";
            Logger.LogInformation(log);

            await Task.Delay(0);
            string[] args = new[] { "x", "y" };
            //-------------------------------------------------------------
            var watch = new Stopwatch();
            //Config Service
            var services = new ServiceCollection();
            TaskStartUp.ConfigureServices(services);
           
            var serviceProvider = services.BuildServiceProvider();
              
            //await ScheduleFileFlushTask.RunTask(args, 1);
             
            await CarParkingScheduleTask.RunTask(args, _ParkingSetting.IntervalMinutes);
 
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.AutoReset = true;
            timer.Interval = 60000*60;  //per one hour
            timer.Elapsed += new ElapsedEventHandler(Tick);
            timer.Start();
        }
          
        public static void Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (needToClearCount > 60)
            {
                needToClearCount = 0;
                Console.Clear(); 
            } 
            string loggerLine =$"[{ DateTime.Now:yyyy-MM-dd HH:mm:ss fff}] [SYSTEM IS RUNNING][TICK CHECK][{needToClearCount}]"; 
            Logger.LogInformation(loggerLine);

            needToClearCount++;
        }

        public override void Dispose()
        {
            // DO YOUR STUFF HERE
        }
          
    }

    // 
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //
    //

}
    
